package com.example.test;


import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@Slf4j
@RestController
public class MinioController {

    @Autowired
    MinioClient minioClient;

    private static String bucketName = "image";

    //上传文件到minio服务
    @PostMapping("upload")
    public String upload(@RequestParam("fileName") MultipartFile file) {
        try {
            InputStream is = file.getInputStream(); //得到文件流
            String fileName = file.getOriginalFilename(); //文件名
            String contentType = file.getContentType();  //类型
            minioClient.putObject(bucketName, fileName, is, contentType); //把文件放置Minio桶(文件夹)
            return "上传成功";
        } catch (Exception e) {
            log.error(e.getMessage());
            return "上传失败";
        }
    }

    //下载minio服务的文件
    @GetMapping("download")
    public String download(HttpServletResponse response) {
        try {
            InputStream fileInputStream = minioClient.getObject(bucketName, "1.jpeg");
            response.setHeader("Content-Disposition", "attachment;filename=" + "1.jpg");
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream, response.getOutputStream());
            return "下载完成";
        } catch (Exception e) {
            return "下载失败";
        }
    }

    //获取minio文件的下载地址
    @GetMapping("url")
    public String getUrl() {
        try {
            String url = minioClient.presignedGetObject(bucketName, "1.jpeg");
            return url;
        } catch (Exception e) {
            return "获取失败";
        }
    }


    /**
     * 删除⽂件
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @throws Exception https://docs.minio.io/cn/java-client-apireference.html#removeObject
     */
    public void removeObject(String bucketName, String objectName) throws Exception {
        minioClient.removeObject(bucketName, objectName);
    }
}
